package com.bdqn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserController
 *
 * @author LILIBO
 * @since 2023-12-18
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    // @RequiresPermissions("用户列表")
    @RequestMapping("/list")
    public String list(Model model, String usrName, Long roleId, @RequestParam(required = false, defaultValue = "1") Long pageIndex) {
        // ① 数据回显
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);

        // ② 填充角色下拉框
        List<Role> roles = roleService.getAllRole();
        model.addAttribute("roles", roles); // 将数据设置到作用域

        // ③ 根据条件进行分页查询
        Page page = new Page(pageIndex, 5);
        Page<User> userPager = userService.getPage(usrName, roleId, page);
        model.addAttribute("userPager", userPager); // 将数据设置到作用域

        // ④ 跳转页面
        return "user/list";
    }

    /**
     * 使用@RequiresPermissions("用户添加")表示有perms[用户添加]权限才能访问该方法
     *
     * @param model
     * @return
     */
    // @RequiresPermissions("用户添加")
    @GetMapping("/add")
    public String toAdd(Model model) {
        List<Role> roles = roleService.getAllRole();
        model.addAttribute("roles", roles); // 将数据设置到作用域
        return "user/add";
    }

    @GetMapping("/edit")
    public String toEdit(Model model, Long usrId) {
        List<Role> roles = roleService.getAllRole();
        model.addAttribute("roles", roles); // 将数据设置到作用域

        // 调用Service层方法获取用户对象
        User user = userService.getUser(usrId);
        model.addAttribute("user", user);

        return "user/edit";
    }

    @GetMapping("/check")
    @ResponseBody
    public Map check(String usrName) {
        Map<String, String> jsonMap = new HashMap<>();
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("usr_name", usrName);
        User checkUser = userService.getOne(qw);
        jsonMap.put("result", String.valueOf(checkUser != null));
        return jsonMap;
    }

    @PostMapping("/save")
    public String save(User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("usr_name", user.getUsrName());
        User checkUser = userService.getOne(qw);
        if ((user.getUsrId() == null && checkUser != null) || (user.getUsrId() != null && checkUser != null && !user.getUsrId().equals(checkUser.getUsrId()))) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print("<script>alert('用户名不能重复，请重新添加。');location.href='" + request.getContextPath() + "/user/list';</script>");
            out.flush();
            out.close();
            return null;
        }

        // 保存或修改用户数据
        User result = userService.saveUser(user);
        // 重定向的方式跳转到列表页面
        return "redirect:/user/list";
    }

    // @RequiresPermissions("L060103")
    @PostMapping("/del/{usrId}")
    @ResponseBody // Ajax方法，将数据直接转换为json格式返回
    public Map del(@PathVariable("usrId") Long usrId) {
        Map<String, String> jsonMap = new HashMap<>();
        boolean result = userService.removeById(usrId);
        jsonMap.put("result", String.valueOf(result));
        return jsonMap;
    }

}
